const https = require('https');
const sqlconnnect = require('./sqlconnnect');
const { formatTime } = require('./util')
/////雪花算法生成
const snowflake = require('./snowflake')
module.exports = function(app){
    /////登录拦截中间键
    function loginRouter(req, res, next){
        let token = req.headers.token
        if(token){
            sqlconnnect(`select * from session where id = ${token}`).then(ret => {
                ////注册成功返回新用户
                
                if(ret.length){
                    let session = ret[0]
                    req.session = {
                        userId:session.userId,
                        userName:session.userName
                    }
                    next()
                }else{
                    res.status(406).send({errorMsg:'当前用户未登录'})
                }
            })
        }else{
            res.status(405).send({errorMsg:'缺少token，请先进行登录'})
        }
    }

    ////拦截中间键，所有接口只有登录才能获取数据
    app.use('/wx',loginRouter)


    ///微信登录
    app.get('/wxlogin',(req, res,next) => {///创建服务
        let code = req.query.code
        let appid = 'wx84950800da73de31'
        let secret = '0d25d00cf96327d1c9e514345617f8fd'
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
            ret.on('data', (ret) => {
                ret = JSON.parse(ret.toString())
                let openid = ret.openid
                if(!openid){
                res.send({errorMsg: ret.errorMsg || '获取openid错误'})  
                }else{
                    let queryMember = `select * from member where openId = '${openid}'`
                    sqlconnnect(queryMember).then(membersRet => {
                        // console.log(membersRet)
                        if(membersRet.length){////用户已经存在
                            ////挂载到req
                            req.member = membersRet[0]
                            next()                        
                        }else{/////用户不存在,使用openid注册用户
                            sqlconnnect(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
                                ////注册成功返回新用户
                                sqlconnnect(queryMember).then(newMember =>{
                                    req.member = membersRet[0]
                                    next()  
                                })
                            })
                        }
                    })
                }
                
            });

            }).on('error', (e) => {
                // console.error(e);
                res.send({errorMsg:'获取openid失败'})
            }
        );
    },(req,res) => {
        let token = snowflake()/////通过雪花算法得到token
        let member = req.member
        // tokens[token] = member
        sqlconnnect(`INSERT INTO session(id, userId, userName, inTime, platform) VALUES(${token}, '${member._id}', '${member.nickName}', '${formatTime(new Date())}', 'wx')`).then(ret => {
            // tokens[token] = member
            res.send({
                nickName: member.nickName,
                token,
                openId: member.openId,
                avatarUrl: member.avatarUrl,
                _id: member._id
            })
        })
    })
    /////更新用户
    app.put('/wx/member',(req,res)=> {
        let userInfo = req.body
        sqlconnnect(`update member set nickName = '${userInfo.nickName}',avatarUrl='${userInfo.avatarUrl}' where _id = ${userInfo._id}`).then(ret => {
            console.log(ret)
                res.send({})
            
        })
    })
    ////获取收获地址列表必填
    ////用户ID
    app.get('/wx/address',loginRouter,(req,res) => {1
        if(req.session.userId){
            sqlconnnect(`select * from address where state = 1 and memberId = ${req.session.userId}`).then(ret => {
                res.send(ret)      
            })
        }else{
            res.send({errorMsg:'请传入memberId'})
        }
        
    })

    //////新增收货地址
    app.post('/wx/address',(req,res) => {
        if(req.body.memberId && req.body.receiver && req.body.phone && req.body.city){
            sqlconnnect(`INSERT INTO address(state, memberId, receiver, phone, city, area) VALUES(1, '${req.body.memberId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}' )`).then(ret => {
                res.send(ret)
                
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
        
    })
    ////////修改收货地址

    app.put('/wx/address',(req,res) => {
        if(req.body.addressId){
            let updateKey = ['receiver', 'phone', 'city', 'area']
            let updateValues = []
            for(let i = 0; i < updateKey.length; i++){
                let key = updateKey[i], value = req.body[key]
                if(value) updateValues.push(`${key} = '${value}'`)
            }
            sqlconnnect(`UPDATE address set ${updateValues.join(',')} where _id = ${req.body.addressId}`).then(ret => {
                res.send(ret)
                
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
        
    })

    /////修改默认地址
    ////传入addressID 主码_id必填
    ////isDefault 是否默认 非必填
    ////传入memberID 用户  必填
    app.put('/wx/address/default',(req,res)=>{
        let addressId = req.body.addressId, memberId = req.body.memberId, isDefault = req.body.isDefault == 1 ? 1 : 0
        if(addressId && memberId){
            if(isDefault == 1){////设置默认地址
                ////取消其他默认地址
                sqlconnnect(`UPDATE address set isDefault = 0 where isDefault = 1 AND memberId = ${memberId}`).then(ret =>{
                    sqlconnnect(`UPDATE address set isDefault = 1 where _id = ${addressId}`).then(ret =>{
                        res.send(ret)
                    })    
                })   
            }else{/////取消默认地址
                sqlconnnect(`UPDATE address set isDefault = 0 where _id = ${addressId}`).then(ret =>{
                    res.send(ret)
                })  
            }
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    /////删除地址 逻辑删除
    app.delete('/wx/address',(req, res) => {
        let addressId = req.body.addressId
        if(addressId){
            sqlconnnect(`UPDATE address set state = 0 where _id = ${addressId}`).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg: '传入参数错误'})
        }
    })

    ////获取收获地址详情
    ////addressId 地址
    app.get('/wx/address/detail',(req,res) => {
        if(req.query.addressId){
            sqlconnnect(`select * from address where _id = ${req.query.addressId}`).then(ret => {
                res.send(ret.length ? ret[0] : {errorMsg: '为获取到地址详情'})      
            })
        }else{
            res.send({errorMsg:'请传入addressId'})
        }
        
    })
}
